﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;
using System.Reflection;

namespace EncoderTester
{
    public class RadioCheckedConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return (parameter == null);
            }
            if (parameter == null) return false;

            return (value.ToString() == parameter.ToString());
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool? ischecked = value as bool?;
            if (ischecked == null) return null;

            if (ischecked.GetValueOrDefault())
            {
                if (targetType == typeof(string)) return parameter;

                object newVal = (targetType.IsValueType) ? Activator.CreateInstance(targetType) : null;
                MethodInfo mi = targetType.GetMethod("TryParse", new Type[] { typeof(String), targetType.MakeByRefType() });
                object[] paramsArray = new object[] { parameter, newVal };
                if (mi != null && (bool)mi.Invoke(null, paramsArray))
                {
                    return paramsArray[1];
                }
            }
            return DependencyProperty.UnsetValue;
        }

        #endregion
    }
}
